let http = require('http');


function express() {
  // 返回值 app
  let funcs = [];

  // 每次有客户端请求的时候才会走app 方法
  let app = function (req, res) {
    let i = 0;

    function next() {
      let task = funcs[i++];

      if (!task) {
        return
      }
      task(req, res, next);
    }

    next();
  };

  /**
   * 参数: middleware 中间件
   * middleware(req,res,next)
   */
  app.use = function (task) {
    funcs.push(task);
  };

  return app;
}

let app = express();
http.createServer(app).listen(3000, function () {
  console.log('listening 3000...');
});


function middleware1(req, res, next) {
  console.log('middleware1', 'before next');
  next();
  console.log('middleware1', 'after next');
}

function middleware2(req, res, next) {
  console.log('middleware2', 'before next');
  next();
  console.log('middleware2', 'after next');
}

function middleware3(req, res, next) {
  console.log('middleware3', 'before next');
  next();
  console.log('middleware3', 'after next');
}

app.use(middleware1);
app.use(middleware2);
app.use(middleware3);
